package com.jcl.recruit.core.config;

import com.jcl.core.db.DynamicDataSource;
import com.jcl.core.db.config.DataSourceConfiguration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * springboot集成mybatis的基本入口 1）创建数据源(如果采用的是默认的tomcat-jdbc数据源，则不需要)
 * 2）创建SqlSessionFactory 3）配置事务管理器，除非需要使用事务，否则不用配置
 */
@Configuration // 该注解类似于spring配置文件
@EnableTransactionManagement
@MapperScan(basePackages = "com.jcl.recruit.*.mapper")
public class DataSourceConfig {

    static final String PREFIX = "spring.datasource";
    static final String PACKAGE = "com.jcl.recruit.*.model";
    static final String MAPPER_LOCATION = "/mybatis-config.xml";

    @Autowired
    private Environment env;

    @Bean
    public DataSourceConfiguration dataSourceConfiguration() {
        DataSourceConfiguration configuration = new DataSourceConfiguration(PREFIX,
                PACKAGE, MAPPER_LOCATION, env);
        return configuration;
    }

    /**
     * 创建默认数据源
     */
    @Bean
    public DataSource consoleDataSource(DataSourceConfiguration configuration) throws Exception {
        return configuration.consoleDataSource();
    }

    /**
     * @Primary 该注解表示在同一个接口有多个实现类可以注入的时候，默认选择哪一个，而不是让@autowire注解报错
     * @Qualifier 根据名称进行注入，通常是在具有相同的多个类型的实例的一个注入（例如有多个DataSource类型的实例）
     */
    @Bean
    @Primary
    public DynamicDataSource dataSource(@Qualifier("consoleDataSource") DataSource consoleDataSource,
                                        DataSourceConfiguration configuration) {
        return configuration.dataSource(consoleDataSource);
    }

    /**
     * 根据数据源创建SqlSessionFactory
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DynamicDataSource ds,
                                               DataSourceConfiguration configuration) throws Exception {
        return configuration.sqlSessionFactory(ds);
    }

    /**
     * 配置事务管理器
     */
    @Bean
    public DataSourceTransactionManager transactionManager(DynamicDataSource dataSource,
                                                           DataSourceConfiguration configuration) throws Exception {
        return configuration.transactionManager(dataSource);
    }


}